package ourFilter;

import interfaces.Writeable;

import java.awt.BorderLayout;
import java.awt.Container;
import java.io.StreamCorruptedException;
import java.sql.Timestamp;
import java.util.Date;

import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;

import com.sun.media.jai.widget.DisplayJAI;

import pipe.Pipe;
import filter.Source;

public class OurSource<T> extends Source<PlanarImage> {

	private String path;
	private Writeable<PlanarImage> out;

	public OurSource(String path, Pipe<PlanarImage> out) {
		this.path = path;
		out.setIn(this);
		this.out = out;
	}

	@Override
	public void run() {
		System.out.println("started " + new Timestamp(new Date().getTime()));
		PlanarImage image = null;
		try {
			image = this.read();
			try {
				out.write(image);
			} catch (StreamCorruptedException e) {
				e.printStackTrace();
			}

		} catch (StreamCorruptedException e1) {
			e1.printStackTrace();
		}
		System.out.println("finished " + new Timestamp(new Date().getTime()));

	}

	@Override
	public PlanarImage read() throws StreamCorruptedException {
		PlanarImage image = JAI.create("fileload", path);
		//showGui(image);
		return image;
	}
	private void showGui(PlanarImage image){
		//Display info
		String imageInfo = "Dimensions: " + image.getWidth() + "x" + image.getHeight() + " Bands:" + image.getNumBands();
		
		JFrame frame = new JFrame();
		frame.setTitle("Display Result Image");

		// Get the JFrameí ContentPane.
		Container contentPane = frame.getContentPane();
		contentPane.setLayout(new BorderLayout());


		// Create an instance of DisplayJAI.
		DisplayJAI dj = new DisplayJAI(image);

		// Add to the JFrameí ContentPane an instance of JScrollPane
		// containing the DisplayJAI instance.
		contentPane.add(new JScrollPane(dj), BorderLayout.CENTER);

		// Add a text label with the image information.
		contentPane.add(new JLabel(imageInfo), BorderLayout.SOUTH);

		// Set the closing operation so the application is finished.
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(image.getWidth() + 10, image.getHeight() + 50); // adjust the frame size.
		frame.setVisible(true); // show the frame.
	}

}
